package com.atguigu.daijia.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSON;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.customer.mapper.CustomerInfoMapper;
import com.atguigu.daijia.customer.mapper.CustomerLoginLogMapper;
import com.atguigu.daijia.customer.service.CustomerInfoService;
import com.atguigu.daijia.model.entity.customer.CustomerInfo;
import com.atguigu.daijia.model.entity.customer.CustomerLoginLog;
import com.atguigu.daijia.model.form.customer.UpdateWxPhoneForm;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Autowired
    private WxMaService wxMaService;
    
    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private CustomerLoginLogMapper customerLoginLogMapper;


    /**
     * @description: 微信小程序登录接口 根据后台id
     * @author: xiaoxie
     * @date: 2024/10/23 20:03
     * @param: [code] 后台id
     * @return: openid 微信接口返回的id
     **/
    @Override
    public Long login(String code) {
      //1.获取openid
        String openid = null;
        try{
            WxMaJscode2SessionResult sessionInfo = wxMaService
                                                   .getUserService()
                                                   .getSessionInfo(code);
            openid = sessionInfo.getOpenid();
            log.info("【小程序授权】openId={}",openid);
        }catch (Exception e){
            log.warn("小程序授权出现异常: {}",ResultCodeEnum.DATA_ERROR.getMessage());
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        //2.根据openid查询数据库
        LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerInfo::getWxOpenId,openid);
        CustomerInfo customerInfo = customerInfoMapper.selectOne(queryWrapper);
        //3.如果数据库中没有查到openid对应的数据
        if(null == customerInfo) {
            //4.把未注册的账户注册
            customerInfo = new CustomerInfo();
            customerInfo.setWxOpenId(openid);
            customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            this.save(customerInfo);
        }
        //5.写入日志
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录");
        customerLoginLogMapper.insert(customerLoginLog);
        //6.返回用户id
        return customerInfo.getId();
    }

   /**
    * @description: 获取客户登录信息
    * @author: xiaoxie
    * @date: 2024/10/23 20:04
    * @param: [customerId] 用户id
    * @return: CustomerLoginVo 用户详细信息
    **/
    @Override
    public CustomerLoginVo getCustomerInfo(Long customerId) {
      //1.根据id查询数据库,获得数据库存储的信息
        CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
        if(null == customerInfo) {
            log.warn("调用的id为: {}",customerId);
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        //2.将信息转换为 CustomerLoginVo
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();
        //使用这个工具类可以把两个类中相同的数据复制一份.
        BeanUtils.copyProperties(customerInfo,customerLoginVo);
        //判断电话号码是否为空
        customerLoginVo.setIsBindPhone(StringUtils.hasText(customerInfo.getPhone()));
        return customerLoginVo;
    }

    //更新客户微信手机号码
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        //1 根据code值获取微信绑定手机号码
//        try {
//            WxMaPhoneNumberInfo phoneNoInfo =
//                    wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
//            String phoneNumber = phoneNoInfo.getPhoneNumber();
//
//            //更新用户信息
//            Long customerId = updateWxPhoneForm.getCustomerId();
//            CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
//            customerInfo.setPhone(phoneNumber);
//            customerInfoMapper.updateById(customerInfo);
//            return true;
//        } catch (WxErrorException e) {
//            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
//        }
        return true;
    }

    @Override
    public String getCustomerOpenId(Long customerId) {
        LambdaQueryWrapper<CustomerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerInfo::getId,customerId);
        CustomerInfo customerInfo = customerInfoMapper.selectOne(wrapper);
        return customerInfo.getWxOpenId();
    }

}
